package cn.wqb.bpp.common.jwt;

import cn.wqb.bpp.common.utils.LogUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import static com.alibaba.fastjson.JSONObject.parseObject;
import static com.alibaba.fastjson.JSONObject.toJSONString;

public class TokenUtils {

    private static final String COOKIE_PREFIX = "wallet";

    /**
     * 从Request里组织创建一个Token实体
     *
     * @return
     */
    public static Token getTokenFromRequest(HttpServletRequest request) {
        String tokenStr = getValueFromCookie(request, "token");
        if (tokenStr != null) {
            try {
                tokenStr = URLDecoder.decode(tokenStr, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (!"{".equals(tokenStr.substring(0, 1))) {
                LogUtils.instance(TokenUtils.class).info("Token不是一个有效的Json，tokenStr:" + tokenStr);
                return null;
            }
            Token token = null;
            try {
                token = parseObject(tokenStr, Token.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return token;
        }
        return null;
    }

    /**
     * 把新Token刷新到Cookie
     *
     * @param token
     * @param response
     */
    public static void updateTokenToCookie(HttpServletResponse response, Token token) {
        if (token == null) {
            LogUtils.instance(TokenUtils.class).info("token为空，未写入Cookie");
            return;
        }
        String tokenStr = toJSONString(token);
        try {
            tokenStr = URLEncoder.encode(tokenStr, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Cookie cookie = new Cookie(COOKIE_PREFIX + "-token", tokenStr);
        cookie.setPath("/");
        cookie.setMaxAge(token.getExpireSeconds());
        response.addCookie(cookie);
    }

    /**
     * 把Token从Cookie里移除
     *
     * @param response
     */
    public static void removeTokenFromCookie(HttpServletResponse response) {
        Cookie cookie = new Cookie(COOKIE_PREFIX + "-token", "");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    private static String getValueFromCookie(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if (cookie.getName().equals(COOKIE_PREFIX + "-" + key)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

}